/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hello;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;

/**
 * @author Fatec
 */
public class VisualMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private java.util.Hashtable __previousDisplayables = new java.util.Hashtable();
    private List ficheiroDeAnotacoesList;
    private List adicionarNoFicheiroList;
    private TextBox textBox;
    private List ficheirosList;
    private Form criarFicheiroForm;
    private TextField novoFicheiroTextField;
    private List anotacoesList;
    private List confirmaExclusaoList;
    private Command exitCommand;
    private Command adicionarAnotacaoCommand;
    private Command criarNovoFicheiroCommand;
    private Command cancelarAnotacaoCommand;
    private Command cancelarAdicionarNoFicheiroCommand;
    private Command cancelarCriarFicheiroCommand;
    private Command backCommand1;
    private Command backCommand;
    private Command excluirFicheiroCommand;
    private Command excluirFicheiroCommand2;
    private Command excluirNotaCommand;
    //</editor-fold>//GEN-END:|fields|0|
    private RecordStore ficheirosStore;
    private RecordStore notasStore;
    private int[][] arrayDeFicheiros;
    private int[] arrayDeNotas;
    private List listaDoElementoExluido;
    public class Lista {

        public class Item {

            Item proximoItem = null;
            int RecordID;

            public Item(int RecordID) {
                this.RecordID = RecordID;

            }
        }
        int numeroDeItens = 0;
        public Item primeiroItem;
        public Item ultimoItem;

        public Lista() {
            numeroDeItens = 0;
        }

        public void adicionarItem(int RecordID) {
            if (primeiroItem == null) {
                primeiroItem = new Item(RecordID);
                ultimoItem = primeiroItem;
                numeroDeItens++;
            } else {
                ultimoItem.proximoItem = new Item(RecordID);
                ultimoItem = ultimoItem.proximoItem;
                numeroDeItens++;
            }

        }

        public int retornaItens() {
            
                int id = primeiroItem.RecordID;
                primeiroItem = primeiroItem.proximoItem;
                return id;
            
        }
    }

    /**
     * The VisualMIDlet constructor.
     */
    public VisualMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    /**
     * Switches a display to previous displayable of the current displayable.
     * The <code>display</code> instance is obtain from the <code>getDisplay</code> method.
     */
    private void switchToPreviousDisplayable() {
        Displayable __currentDisplayable = getDisplay().getCurrent();
        if (__currentDisplayable != null) {
            Displayable __nextDisplayable = (Displayable) __previousDisplayables.get(__currentDisplayable);
            if (__nextDisplayable != null) {
                switchDisplayable(null, __nextDisplayable);
            }
        }
    }
    //</editor-fold>//GEN-END:|methods|0|
    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getFicheiroDeAnotacoesList());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        Displayable __currentDisplayable = display.getCurrent();
        if (__currentDisplayable != null  &&  nextDisplayable != null) {
            __previousDisplayables.put(nextDisplayable, __currentDisplayable);
        }
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == adicionarNoFicheiroList) {//GEN-BEGIN:|7-commandAction|1|31-preAction
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|1|31-preAction
                // write pre-action user code here
                adicionarNoFicheiroListAction();//GEN-LINE:|7-commandAction|2|31-postAction
                // write post-action user code here
            } else if (command == cancelarAdicionarNoFicheiroCommand) {//GEN-LINE:|7-commandAction|3|88-preAction
                // write pre-action user code here
                switchDisplayable(null, getTextBox());//GEN-LINE:|7-commandAction|4|88-postAction
                // write post-action user code here
            } else if (command == excluirFicheiroCommand) {//GEN-LINE:|7-commandAction|5|106-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|6|106-postAction
                confirmarExlusao(adicionarNoFicheiroList);
            }//GEN-BEGIN:|7-commandAction|7|97-preAction
        } else if (displayable == anotacoesList) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|7|97-preAction
                // write pre-action user code here
                anotacoesListAction();//GEN-LINE:|7-commandAction|8|97-postAction
                // write post-action user code here
            } else if (command == backCommand1) {//GEN-LINE:|7-commandAction|9|103-preAction
                // write pre-action user code here
                switchDisplayable(null, getFicheirosList());//GEN-LINE:|7-commandAction|10|103-postAction
                // write post-action user code here
            } else if (command == excluirNotaCommand) {//GEN-LINE:|7-commandAction|11|110-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|12|110-postAction
                confirmarExlusao(anotacoesList);
                        // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|13|112-preAction
        } else if (displayable == confirmaExclusaoList) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|13|112-preAction
                // write pre-action user code here
                confirmaExclusaoListAction();//GEN-LINE:|7-commandAction|14|112-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|15|91-preAction
        } else if (displayable == criarFicheiroForm) {
            if (command == cancelarCriarFicheiroCommand) {//GEN-END:|7-commandAction|15|91-preAction
                // write pre-action user code here
                switchDisplayable(null, getAdicionarNoFicheiroList());//GEN-LINE:|7-commandAction|16|91-postAction
                // write post-action user code here
            } else if (command == criarNovoFicheiroCommand) {//GEN-LINE:|7-commandAction|17|77-preAction
             if(novoFicheiroTextField.getString().equals("")){
                 exibirAlertaStringVazia();
             }
                else{
                criarFicheiro(codigoDeFicheiroLivre(), novoFicheiroTextField.getString());
                novoFicheiroTextField.setString(null);
                switchDisplayable(null, getAdicionarNoFicheiroList());//GEN-LINE:|7-commandAction|18|77-postAction
                atualizarArrayDeFicheiros(1);
            }// write post-action user code here
            }//GEN-BEGIN:|7-commandAction|19|19-preAction
        } else if (displayable == ficheiroDeAnotacoesList) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|19|19-preAction
                // write pre-action user code here
                ficheiroDeAnotacoesListAction();//GEN-LINE:|7-commandAction|20|19-postAction
                // write post-action user code here
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|21|25-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|22|25-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|23|64-preAction
        } else if (displayable == ficheirosList) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|23|64-preAction
                // write pre-action user code here
                ficheirosListAction();//GEN-LINE:|7-commandAction|24|64-postAction
                // write post-action user code here
            } else if (command == backCommand) {//GEN-LINE:|7-commandAction|25|100-preAction
                // write pre-action user code here
                switchDisplayable(null, getFicheiroDeAnotacoesList());//GEN-LINE:|7-commandAction|26|100-postAction
                // write post-action user code here
            } else if (command == excluirFicheiroCommand2) {//GEN-LINE:|7-commandAction|27|108-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|28|108-postAction
                confirmarExlusao(ficheirosList);
            }//GEN-BEGIN:|7-commandAction|29|61-preAction
        } else if (displayable == textBox) {
            if (command == adicionarAnotacaoCommand) {//GEN-END:|7-commandAction|29|61-preAction
            if(textBox.getString().equals("")){
                exibirAlertaStringVazia();
            }else{
                switchDisplayable(null, getAdicionarNoFicheiroList());//GEN-LINE:|7-commandAction|30|61-postAction
                atualizarArrayDeFicheiros(1);
                }// write post-action user code here
            } else if (command == cancelarAnotacaoCommand) {//GEN-LINE:|7-commandAction|31|85-preAction
                // write pre-action user code here
                switchDisplayable(null, getFicheiroDeAnotacoesList());//GEN-LINE:|7-commandAction|32|85-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|33|7-postCommandAction
        }//GEN-END:|7-commandAction|33|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|34|
    //</editor-fold>//GEN-END:|7-commandAction|34|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: ficheiroDeAnotacoesList ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initiliazed instance of ficheiroDeAnotacoesList component.
     * @return the initialized component instance
     */
    public List getFicheiroDeAnotacoesList() {
        if (ficheiroDeAnotacoesList == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            ficheiroDeAnotacoesList = new List("Ficheiro de Anota\u00E7\u00F5es", Choice.IMPLICIT);//GEN-BEGIN:|17-getter|1|17-postInit
            ficheiroDeAnotacoesList.append("Adicionar Anota\u00E7\u00E3o", null);
            ficheiroDeAnotacoesList.append("Consultar Anota\u00E7\u00F5es", null);
            ficheiroDeAnotacoesList.addCommand(getExitCommand());
            ficheiroDeAnotacoesList.setCommandListener(this);
            ficheiroDeAnotacoesList.setSelectedFlags(new boolean[] { false, false });//GEN-END:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return ficheiroDeAnotacoesList;
    }
    //</editor-fold>//GEN-END:|17-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: ficheiroDeAnotacoesListAction ">//GEN-BEGIN:|17-action|0|17-preAction
    /**
     * Performs an action assigned to the selected list element in the ficheiroDeAnotacoesList component.
     */
    public void ficheiroDeAnotacoesListAction() {//GEN-END:|17-action|0|17-preAction
        // enter pre-action user code here
        String __selectedString = getFicheiroDeAnotacoesList().getString(getFicheiroDeAnotacoesList().getSelectedIndex());//GEN-BEGIN:|17-action|1|22-preAction
        if (__selectedString != null) {
            if (__selectedString.equals("Adicionar Anota\u00E7\u00E3o")) {//GEN-END:|17-action|1|22-preAction
                // write pre-action user code here
                switchDisplayable(null, getTextBox());//GEN-LINE:|17-action|2|22-postAction
                // write post-action user code here
            } else if (__selectedString.equals("Consultar Anota\u00E7\u00F5es")) {//GEN-LINE:|17-action|3|23-preAction
                // write pre-action user code here
                switchDisplayable(null, getFicheirosList());//GEN-LINE:|17-action|4|23-postAction
                atualizarArrayDeFicheiros(0);// write post-action user code here
            }//GEN-BEGIN:|17-action|5|17-postAction
        }//GEN-END:|17-action|5|17-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|17-action|6|
    //</editor-fold>//GEN-END:|17-action|6|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: adicionarNoFicheiroList ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initiliazed instance of adicionarNoFicheiroList component.
     * @return the initialized component instance
     */
    public List getAdicionarNoFicheiroList() {
        if (adicionarNoFicheiroList == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            adicionarNoFicheiroList = new List("Adicionar no ficheiro...", Choice.IMPLICIT);//GEN-BEGIN:|30-getter|1|30-postInit
            adicionarNoFicheiroList.addCommand(getCancelarAdicionarNoFicheiroCommand());
            adicionarNoFicheiroList.addCommand(getExcluirFicheiroCommand());
            adicionarNoFicheiroList.setCommandListener(this);//GEN-END:|30-getter|1|30-postInit

            // write post-init user code here
        }//GEN-BEGIN:|30-getter|2|
        return adicionarNoFicheiroList;
    }
    //</editor-fold>//GEN-END:|30-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: adicionarNoFicheiroListAction ">//GEN-BEGIN:|30-action|0|30-preAction
    /**
     * Performs an action assigned to the selected list element in the adicionarNoFicheiroList component.
     */
    public void adicionarNoFicheiroListAction() {//GEN-END:|30-action|0|30-preAction
        // enter pre-action user code here
        String __selectedString = getAdicionarNoFicheiroList().getString(getAdicionarNoFicheiroList().getSelectedIndex());//GEN-LINE:|30-action|1|30-postAction
        if (__selectedString.equals("Criar novo ficheiro")) {
            switchDisplayable(null, getCriarFicheiroForm());

        } else {
            gravarAnotacao(arrayDeFicheiros[getAdicionarNoFicheiroList().getSelectedIndex()][1], textBox.getString());
            textBox.setString(null);
            switchDisplayable(null, getFicheiroDeAnotacoesList());
        }
    }//GEN-BEGIN:|30-action|2|
    //</editor-fold>//GEN-END:|30-action|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|24-getter|0|24-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
            exitCommand = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|24-getter|1|24-postInit
            // write post-init user code here
        }//GEN-BEGIN:|24-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|24-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textBox ">//GEN-BEGIN:|58-getter|0|58-preInit
    /**
     * Returns an initiliazed instance of textBox component.
     * @return the initialized component instance
     */
    public TextBox getTextBox() {
        if (textBox == null) {//GEN-END:|58-getter|0|58-preInit
            // write pre-init user code here
            textBox = new TextBox("Anota\u00E7\u00E3o", "", 500, TextField.ANY);//GEN-BEGIN:|58-getter|1|58-postInit
            textBox.addCommand(getAdicionarAnotacaoCommand());
            textBox.addCommand(getCancelarAnotacaoCommand());
            textBox.setCommandListener(this);
            textBox.setInitialInputMode("UCB_BASIC_LATIN");//GEN-END:|58-getter|1|58-postInit
            // write post-init user code here
        }//GEN-BEGIN:|58-getter|2|
        return textBox;
    }
    //</editor-fold>//GEN-END:|58-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: adicionarAnotacaoCommand ">//GEN-BEGIN:|60-getter|0|60-preInit
    /**
     * Returns an initiliazed instance of adicionarAnotacaoCommand component.
     * @return the initialized component instance
     */
    public Command getAdicionarAnotacaoCommand() {
        if (adicionarAnotacaoCommand == null) {//GEN-END:|60-getter|0|60-preInit
            // write pre-init user code here
            adicionarAnotacaoCommand = new Command("Ok", Command.OK, 0);//GEN-LINE:|60-getter|1|60-postInit
            // write post-init user code here
        }//GEN-BEGIN:|60-getter|2|
        return adicionarAnotacaoCommand;
    }
    //</editor-fold>//GEN-END:|60-getter|2|
    //</editor-fold>
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: ficheirosList ">//GEN-BEGIN:|63-getter|0|63-preInit
    /**
     * Returns an initiliazed instance of ficheirosList component.
     * @return the initialized component instance
     */
    public List getFicheirosList() {
        if (ficheirosList == null) {//GEN-END:|63-getter|0|63-preInit
            // write pre-init user code here
            ficheirosList = new List("Ficheiros", Choice.IMPLICIT);//GEN-BEGIN:|63-getter|1|63-postInit
            ficheirosList.addCommand(getBackCommand());
            ficheirosList.addCommand(getExcluirFicheiroCommand2());
            ficheirosList.setCommandListener(this);//GEN-END:|63-getter|1|63-postInit
            // write post-init user code here
        }//GEN-BEGIN:|63-getter|2|
        return ficheirosList;
    }
    //</editor-fold>//GEN-END:|63-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: ficheirosListAction ">//GEN-BEGIN:|63-action|0|63-preAction
    /**
     * Performs an action assigned to the selected list element in the ficheirosList component.
     */
    public void ficheirosListAction() {//GEN-END:|63-action|0|63-preAction
        // enter pre-action user code here
        String __selectedString = getFicheirosList().getString(getFicheirosList().getSelectedIndex());//GEN-LINE:|63-action|1|63-postAction
        switchDisplayable(null, getAnotacoesList());
        atualizarArrayDeNotas(arrayDeFicheiros[getFicheirosList().getSelectedIndex()][1]);

        // enter post-action user code here
    }//GEN-BEGIN:|63-action|2|
    //</editor-fold>//GEN-END:|63-action|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: criarFicheiroForm ">//GEN-BEGIN:|67-getter|0|67-preInit
    /**
     * Returns an initiliazed instance of criarFicheiroForm component.
     * @return the initialized component instance
     */
    public Form getCriarFicheiroForm() {
        if (criarFicheiroForm == null) {//GEN-END:|67-getter|0|67-preInit
            // write pre-init user code here
            criarFicheiroForm = new Form("Criar ficheiro", new Item[] { getNovoFicheiroTextField() });//GEN-BEGIN:|67-getter|1|67-postInit
            criarFicheiroForm.addCommand(getCriarNovoFicheiroCommand());
            criarFicheiroForm.addCommand(getCancelarCriarFicheiroCommand());
            criarFicheiroForm.setCommandListener(this);//GEN-END:|67-getter|1|67-postInit
            // write post-init user code here
        }//GEN-BEGIN:|67-getter|2|
        return criarFicheiroForm;
    }
    //</editor-fold>//GEN-END:|67-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: novoFicheiroTextField ">//GEN-BEGIN:|75-getter|0|75-preInit
    /**
     * Returns an initiliazed instance of novoFicheiroTextField component.
     * @return the initialized component instance
     */
    public TextField getNovoFicheiroTextField() {
        if (novoFicheiroTextField == null) {//GEN-END:|75-getter|0|75-preInit
            // write pre-init user code here
            novoFicheiroTextField = new TextField("Nome do novo ficheiro", "", 32, TextField.ANY);//GEN-LINE:|75-getter|1|75-postInit
            // write post-init user code here
        }//GEN-BEGIN:|75-getter|2|
        return novoFicheiroTextField;
    }
    //</editor-fold>//GEN-END:|75-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: criarNovoFicheiroCommand ">//GEN-BEGIN:|76-getter|0|76-preInit
    /**
     * Returns an initiliazed instance of criarNovoFicheiroCommand component.
     * @return the initialized component instance
     */
    public Command getCriarNovoFicheiroCommand() {
        if (criarNovoFicheiroCommand == null) {//GEN-END:|76-getter|0|76-preInit
            // write pre-init user code here
            criarNovoFicheiroCommand = new Command("Ok", Command.OK, 0);//GEN-LINE:|76-getter|1|76-postInit
            // write post-init user code here
        }//GEN-BEGIN:|76-getter|2|
        return criarNovoFicheiroCommand;
    }
    //</editor-fold>//GEN-END:|76-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cancelarAnotacaoCommand ">//GEN-BEGIN:|84-getter|0|84-preInit
    /**
     * Returns an initiliazed instance of cancelarAnotacaoCommand component.
     * @return the initialized component instance
     */
    public Command getCancelarAnotacaoCommand() {
        if (cancelarAnotacaoCommand == null) {//GEN-END:|84-getter|0|84-preInit
            // write pre-init user code here
            cancelarAnotacaoCommand = new Command("Cancelar", Command.CANCEL, 0);//GEN-LINE:|84-getter|1|84-postInit
            // write post-init user code here
        }//GEN-BEGIN:|84-getter|2|
        return cancelarAnotacaoCommand;
    }
    //</editor-fold>//GEN-END:|84-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cancelarAdicionarNoFicheiroCommand ">//GEN-BEGIN:|87-getter|0|87-preInit
    /**
     * Returns an initiliazed instance of cancelarAdicionarNoFicheiroCommand component.
     * @return the initialized component instance
     */
    public Command getCancelarAdicionarNoFicheiroCommand() {
        if (cancelarAdicionarNoFicheiroCommand == null) {//GEN-END:|87-getter|0|87-preInit
            // write pre-init user code here
            cancelarAdicionarNoFicheiroCommand = new Command("Voltar", Command.OK, 0);//GEN-LINE:|87-getter|1|87-postInit
            // write post-init user code here
        }//GEN-BEGIN:|87-getter|2|
        return cancelarAdicionarNoFicheiroCommand;
    }
    //</editor-fold>//GEN-END:|87-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cancelarCriarFicheiroCommand ">//GEN-BEGIN:|90-getter|0|90-preInit
    /**
     * Returns an initiliazed instance of cancelarCriarFicheiroCommand component.
     * @return the initialized component instance
     */
    public Command getCancelarCriarFicheiroCommand() {
        if (cancelarCriarFicheiroCommand == null) {//GEN-END:|90-getter|0|90-preInit
            // write pre-init user code here
            cancelarCriarFicheiroCommand = new Command("Cancelar", Command.CANCEL, 0);//GEN-LINE:|90-getter|1|90-postInit
            // write post-init user code here
        }//GEN-BEGIN:|90-getter|2|
        return cancelarCriarFicheiroCommand;
    }
    //</editor-fold>//GEN-END:|90-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: anotacoesList ">//GEN-BEGIN:|96-getter|0|96-preInit
    /**
     * Returns an initiliazed instance of anotacoesList component.
     * @return the initialized component instance
     */
    public List getAnotacoesList() {
        if (anotacoesList == null) {//GEN-END:|96-getter|0|96-preInit
            // write pre-init user code here
            anotacoesList = new List("Anota\u00E7\u00F5es", Choice.IMPLICIT);//GEN-BEGIN:|96-getter|1|96-postInit
            anotacoesList.addCommand(getBackCommand1());
            anotacoesList.addCommand(getExcluirNotaCommand());
            anotacoesList.setCommandListener(this);//GEN-END:|96-getter|1|96-postInit
            // write post-init user code here
        }//GEN-BEGIN:|96-getter|2|
        return anotacoesList;
    }
    //</editor-fold>//GEN-END:|96-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: anotacoesListAction ">//GEN-BEGIN:|96-action|0|96-preAction
    /**
     * Performs an action assigned to the selected list element in the anotacoesList component.
     */
    public void anotacoesListAction() {//GEN-END:|96-action|0|96-preAction
        // enter pre-action user code here
        String __selectedString = getAnotacoesList().getString(getAnotacoesList().getSelectedIndex());//GEN-LINE:|96-action|1|96-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|96-action|2|
    //</editor-fold>//GEN-END:|96-action|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|99-getter|0|99-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|99-getter|0|99-preInit
            // write pre-init user code here
            backCommand = new Command("Voltar", Command.BACK, 0);//GEN-LINE:|99-getter|1|99-postInit
            // write post-init user code here
        }//GEN-BEGIN:|99-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|99-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand1 ">//GEN-BEGIN:|102-getter|0|102-preInit
    /**
     * Returns an initiliazed instance of backCommand1 component.
     * @return the initialized component instance
     */
    public Command getBackCommand1() {
        if (backCommand1 == null) {//GEN-END:|102-getter|0|102-preInit
            // write pre-init user code here
            backCommand1 = new Command("Voltar", Command.BACK, 0);//GEN-LINE:|102-getter|1|102-postInit
            // write post-init user code here
        }//GEN-BEGIN:|102-getter|2|
        return backCommand1;
    }
    //</editor-fold>//GEN-END:|102-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: excluirFicheiroCommand ">//GEN-BEGIN:|105-getter|0|105-preInit
    /**
     * Returns an initiliazed instance of excluirFicheiroCommand component.
     * @return the initialized component instance
     */
    public Command getExcluirFicheiroCommand() {
        if (excluirFicheiroCommand == null) {//GEN-END:|105-getter|0|105-preInit
            // write pre-init user code here
            excluirFicheiroCommand = new Command("Excluir", Command.OK, 0);//GEN-LINE:|105-getter|1|105-postInit
            // write post-init user code here
        }//GEN-BEGIN:|105-getter|2|
        return excluirFicheiroCommand;
    }
    //</editor-fold>//GEN-END:|105-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: excluirFicheiroCommand2 ">//GEN-BEGIN:|107-getter|0|107-preInit
    /**
     * Returns an initiliazed instance of excluirFicheiroCommand2 component.
     * @return the initialized component instance
     */
    public Command getExcluirFicheiroCommand2() {
        if (excluirFicheiroCommand2 == null) {//GEN-END:|107-getter|0|107-preInit
            // write pre-init user code here
            excluirFicheiroCommand2 = new Command("Excluir", Command.OK, 0);//GEN-LINE:|107-getter|1|107-postInit
            // write post-init user code here
        }//GEN-BEGIN:|107-getter|2|
        return excluirFicheiroCommand2;
    }
    //</editor-fold>//GEN-END:|107-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: excluirNotaCommand ">//GEN-BEGIN:|109-getter|0|109-preInit
    /**
     * Returns an initiliazed instance of excluirNotaCommand component.
     * @return the initialized component instance
     */
    public Command getExcluirNotaCommand() {
        if (excluirNotaCommand == null) {//GEN-END:|109-getter|0|109-preInit
            // write pre-init user code here
            excluirNotaCommand = new Command("Excluir", Command.OK, 0);//GEN-LINE:|109-getter|1|109-postInit
            // write post-init user code here
        }//GEN-BEGIN:|109-getter|2|
        return excluirNotaCommand;
    }
    //</editor-fold>//GEN-END:|109-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: confirmaExclusaoList ">//GEN-BEGIN:|111-getter|0|111-preInit
    /**
     * Returns an initiliazed instance of confirmaExclusaoList component.
     * @return the initialized component instance
     */
    public List getConfirmaExclusaoList() {
        if (confirmaExclusaoList == null) {//GEN-END:|111-getter|0|111-preInit
            // write pre-init user code here
            confirmaExclusaoList = new List("Confirmar Exclus\u00E3o?", Choice.IMPLICIT);//GEN-BEGIN:|111-getter|1|111-postInit
            confirmaExclusaoList.append("N\u00E3o", null);
            confirmaExclusaoList.append("Sim", null);
            confirmaExclusaoList.setCommandListener(this);
            confirmaExclusaoList.setSelectedFlags(new boolean[] { false, false });//GEN-END:|111-getter|1|111-postInit
            // write post-init user code here
        }//GEN-BEGIN:|111-getter|2|
        return confirmaExclusaoList;
    }
    //</editor-fold>//GEN-END:|111-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: confirmaExclusaoListAction ">//GEN-BEGIN:|111-action|0|111-preAction
    /**
     * Performs an action assigned to the selected list element in the confirmaExclusaoList component.
     */
    public void confirmaExclusaoListAction() {//GEN-END:|111-action|0|111-preAction
        // enter pre-action user code here
        String __selectedString = getConfirmaExclusaoList().getString(getConfirmaExclusaoList().getSelectedIndex());//GEN-BEGIN:|111-action|1|114-preAction
        if (__selectedString != null) {
            if (__selectedString.equals("N\u00E3o")) {//GEN-END:|111-action|1|114-preAction
                // write pre-action user code here
                switchToPreviousDisplayable();//GEN-LINE:|111-action|2|114-postAction
                // write post-action user code here
            } else if (__selectedString.equals("Sim")) {//GEN-LINE:|111-action|3|115-preAction
                // write pre-action user code here
//GEN-LINE:|111-action|4|115-postAction
               confirmarExclusao(); // write post-action user code here
            }//GEN-BEGIN:|111-action|5|111-postAction
        }//GEN-END:|111-action|5|111-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|111-action|6|
    //</editor-fold>//GEN-END:|111-action|6|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);


    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(
                true);
        notifyDestroyed();


    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();


        } else {
            initialize();
            startMIDlet();


        }
        midletPaused = false;


    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;


    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void abrirFicheirosStore() throws RecordStoreNotFoundException, RecordStoreException {



        ficheirosStore = RecordStore.openRecordStore("Ficheiros", true);


    }

    public void fecharFicheirosStore() throws RecordStoreException {



        ficheirosStore.closeRecordStore();


    }

    public void abrirNotasStore() throws RecordStoreException {



        notasStore = RecordStore.openRecordStore("notas", true);


    }

    public void fecharNotasStore() throws RecordStoreException {



        notasStore.closeRecordStore();


    }

    public void atualizarArrayDeFicheiros(int cd) {
        if (cd == 1) {
            adicionarNoFicheiroList.deleteAll();
            try {
                abrirFicheirosStore();
                int numeroDeFicheiros = ficheirosStore.getNumRecords();

                arrayDeFicheiros = new int[numeroDeFicheiros][2];

                RecordEnumeration recordEnum = ficheirosStore.enumerateRecords(null, null, true);

                for (int i = 0; i < numeroDeFicheiros; i++) {
                    int id = recordEnum.nextRecordId();
                    byte[] bytes = ficheirosStore.getRecord(id);
                    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                    DataInputStream dis = new DataInputStream(bais);
                    arrayDeFicheiros[i][0] = id;
                    arrayDeFicheiros[i][1] = dis.readInt();
                    adicionarNoFicheiroList.append(dis.readUTF(), null);
                }



                fecharFicheirosStore();
            } catch (Exception e) {
            }
            adicionarNoFicheiroList.append("Criar novo ficheiro", null);
        } else {
            ficheirosList.deleteAll();
            try {
                abrirFicheirosStore();
                int numeroDeFicheiros = ficheirosStore.getNumRecords();

                arrayDeFicheiros = new int[numeroDeFicheiros][2];

                RecordEnumeration recordEnum = ficheirosStore.enumerateRecords(null, null, true);

                for (int i = 0; i < numeroDeFicheiros; i++) {
                    int id = recordEnum.nextRecordId();
                    byte[] bytes = ficheirosStore.getRecord(id);
                    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                    DataInputStream dis = new DataInputStream(bais);
                    arrayDeFicheiros[i][0] = id;
                    arrayDeFicheiros[i][1] = dis.readInt();
                    ficheirosList.append(dis.readUTF(), null);
                }




                fecharFicheirosStore();
            } catch (Exception e) {
            }
        }

    }

    public void gravarAnotacao(int IdDoFicheiro, String anotacao) {
        try {
            abrirNotasStore();



            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);

            dos.writeInt(IdDoFicheiro);
            dos.writeUTF(anotacao);



            byte[] bytes = baos.toByteArray();

            notasStore.addRecord(bytes, 0, bytes.length);


            fecharNotasStore();


        } catch (Exception e) {
        }

    }

    public void atualizarArrayDeNotas(int idDoFicheiro) {
        anotacoesList.deleteAll();
        Lista listaDeNotas = new Lista();


        try {
            abrirNotasStore();

            RecordEnumeration recEnum = notasStore.enumerateRecords(null, null, true);


            while (recEnum.hasNextElement()) {
                int id = recEnum.nextRecordId();


                byte[] bytes = notasStore.getRecord(id);
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                DataInputStream dis = new DataInputStream(bais);


                int ficheiro = dis.readInt();


                if (ficheiro == idDoFicheiro) {
                    anotacoesList.append(dis.readUTF(), null);
                    listaDeNotas.adicionarItem(id);


                }
            }
            fecharNotasStore();


        } catch (Exception e) {
        }
        arrayDeNotas = new int[listaDeNotas.numeroDeItens];


        for (int i = 0; i < arrayDeNotas.length; i++) {
            arrayDeNotas[i] = listaDeNotas.retornaItens();


        }
    }

    public void criarFicheiro(int IdDoFicheiro, String nomeDoFicheiro) {
        try {
            abrirFicheirosStore();


        


        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);


       
            dos.writeInt(IdDoFicheiro);
            dos.writeUTF(nomeDoFicheiro);


        
        byte[] bytes = baos.toByteArray();


       
            ficheirosStore.addRecord(bytes, 0, bytes.length);



        
        


        } catch (Exception e) {
        }


    }

    public void excluirNota(int id) {
        try{
        abrirNotasStore();
        notasStore.deleteRecord(id);
        fecharNotasStore();
        }catch(Exception e){
            
        }
    }

    public void excluirFicheiro(int id) {
        try{
        abrirFicheirosStore();
        ficheirosStore.deleteRecord(id);
        fecharFicheirosStore();
        abrirNotasStore();
        RecordEnumeration recEnum = notasStore.enumerateRecords(null, null, true);
        while(recEnum.hasNextElement()){
            int notaId = recEnum.nextRecordId();
            byte[] bytes = notasStore.getRecord(notaId);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            DataInputStream dis = new DataInputStream(bais);
            if(id==dis.readInt()){
                notasStore.deleteRecord(notaId);
            }
        }
        }catch(Exception e){

        }
    }

    public int codigoDeFicheiroLivre() {
        if (arrayDeFicheiros == null) {
            return 1;


        } else {
            int codigo = arrayDeFicheiros.length + 1;


            boolean repetido = false;


            for (int i = 1; i
                    <= arrayDeFicheiros.length; i++) {
                for (int i2 = 0; i2
                        < arrayDeFicheiros.length; i2++) {
                    if (i == arrayDeFicheiros[i2][1]) {
                        repetido = true;


                        break;


                    }

                }
                if (repetido == false) {
                    codigo = i;


                    break;


                }
                repetido = false;


            }
            return codigo;

        }
    }

    public void exibirAlertaStringVazia(){
        Alert alert = new Alert("Caixa de texto vazia!");
        alert.setString("Você deve digitar algum valor.");
        alert.setTimeout(5000);
        getDisplay().setCurrent(alert);

    }

    public void confirmarExlusao(List list){
        if ((list.size()>0&&list!=adicionarNoFicheiroList)||list.size()>1){
        listaDoElementoExluido = list;
        switchDisplayable(null, getConfirmaExclusaoList());
        confirmaExclusaoList.setSelectedIndex(0, true);
        }

    }
    public void confirmarExclusao(){
        if (listaDoElementoExluido==adicionarNoFicheiroList){
            excluirFicheiro(arrayDeFicheiros[listaDoElementoExluido.getSelectedIndex()][0]);
            switchDisplayable(null, listaDoElementoExluido);
            atualizarArrayDeFicheiros(1);
        }
        else if (listaDoElementoExluido==ficheirosList){
            excluirFicheiro(arrayDeFicheiros[listaDoElementoExluido.getSelectedIndex()][0]);
            switchDisplayable(null, listaDoElementoExluido);
            atualizarArrayDeFicheiros(0);
        }
        else{
            excluirNota(arrayDeNotas[listaDoElementoExluido.getSelectedIndex()]);
            switchDisplayable(null, listaDoElementoExluido);
            atualizarArrayDeNotas(arrayDeFicheiros[listaDoElementoExluido.getSelectedIndex()][1]);
        }
    }
    
}
